package cn.zwx.member.svc.utils;

import cn.zwx.base.exception.BizWrapException;
import cn.zwx.member.svc.domain.enums.MemberCodeEnum;
import cn.zwx.member.svc.domain.warp.ExceptionWrap;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author zhangwenxue
 */
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

    /**
     * token 有效时间
     */
    private Long expire;

    /**
     * refresh token 有效时间
     */
    private Long refreshExpire;

    /**
     * secretKey
     */
    private String secret;

    /**
     * 生成JWT
     * @param mobile mobile
     * @param claims claims
     * @return String
     */
    public String generateToken(String mobile, Map<String,Object> claims) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        // 7天过期
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(mobile)
                .addClaims(claims)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    /**
     * 生成JWT
     * @param mobile mobile
     * @param claims claims
     * @return String
     */
    public String generateRefreshToken(String mobile, Map<String,Object> claims) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * refreshExpire);
        // 7天过期
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(mobile)
                .addClaims(claims)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    /**
     *  解析JWT
     * @param token jwt
     * @return Claims
     */
    public Claims getClaimsByToken(String token) throws BizWrapException {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw ExceptionWrap.wrap(MemberCodeEnum.PARSE_TOKEN_ERROR);
        }
    }

    /**
     * 判断JWT是否过期
     * @param token token
     * @return boolean
     */
    public boolean isTokenExpired(String token) throws BizWrapException {
        final Claims claims = getClaimsByToken(token);
        return claims.getExpiration().before(new Date());
    }
}
